package com.woniuxy.handler;

import com.woniuxy.service.NoticeService;
import com.work.framework.pojo.Notice;
import io.swagger.annotations.Api;
import net.sf.json.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author kyle
 * @date 2019-09-19 16:44
 */
@Api(value = "聊天的基本功能实现")
@ServerEndpoint("/webSocket/{sendUser}")
@Component
public class WebSocketHandler {

    private static ApplicationContext applicationContext;
//    @Resource
    private NoticeService noticeService;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketHandler.applicationContext = applicationContext;
    }

    private static ConcurrentHashMap<Integer, WebSocketHandler> webSocketMap = new ConcurrentHashMap<>();
    private Session session;
    private Integer sendUser;//当前用户
    private Integer toUser;//接收用户
    private String message;//聊天信息

    /**
     * 连接成功建立调用的方法
     * @param session
     * @param sendUser
     */
    @OnOpen
    public void onOpen (Session session, @PathParam(value = "sendUser") Integer sendUser) {
        System.out.println("websocket 建立连接成功" + session);
        this.sendUser = sendUser;
        this.session = session;
        webSocketMap.put(sendUser, this);
    }


    /**
     * 接收到消息调用的方法
     * @param jsonMes
     */
    @OnMessage
    public void onMessage (String jsonMes) throws IOException {

        //解析Json对象
        JSONObject jsonObject = JSONObject.fromObject(jsonMes);
        toUser = Integer.parseInt(jsonObject.getString("toUser"));
        System.out.println("目标用户："+toUser);
        message = jsonObject.getString("message");
        System.out.println("服务端收到来自客户端的消息:" + message);
        WebSocketHandler webSocket = webSocketMap.get(toUser);
        if (null == webSocket) {
            //用户不在线，将消息存数据库
            Notice notice = new Notice(sendUser, toUser, 1, message, 1, null, "");
            noticeService = applicationContext.getBean(NoticeService.class);
            Boolean res = noticeService.addChatNotice(notice);
            System.out.println("存储消息到数据库："+res);
            return;
        }
        webSocket.sendMessage (message);
    }

    @OnError
    public void onError (Session session, Throwable error) {
        try {
            session.close();
            error.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose (Session session) {
        webSocketMap.remove(sendUser);
        try {
            session.close();
            System.out.println("websocket连接已经关闭"+session);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将消息发送到指定用户
     * @param message
     * @throws IOException
     */
    public void sendMessage (String message) throws IOException {
        if (null != message) {
            //将消息发送到目标用户
            this.session.getBasicRemote().sendText(message);
        }
    }

}
